<?php
declare (strict_types=1);

namespace app\middleware;

use app\models\user\UserModel;
use think\facade\Db;


class ApiAuth
{

    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        try {
            $token = $request->header('token');
            if (empty($token)) {
                throw new \Exception('token不能为空');
            }
            $userInfo = UserModel::where('token', $token)->find();
            if (empty($userInfo)) {
                throw new \Exception('令牌错误');
            }
            if ($userInfo['valid_time'] <= time()) {
                throw new \Exception('token已失效');
            }
            $request->userId = $userInfo['id'];
            $request->userInfo = $userInfo;
        } catch (\Exception $exception) {
            return json()->data(['code' => -1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}
